<script setup lang='ts'>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { baseList, useExportStatistics, usePageInfo } from '@fl/api/fangjiaohui'
import { SearchForm, SearchTable } from '@fl/components'

import Charts from './charts.vue'
import { APPOINTMENT_DICT, CUSTOMER_DICT, HOUSING_DICT } from './constant'
import panelGroup from './panel-group.vue'

const { push } = useRouter()

type IState = {
    buildingName: string
    customerName: string
    selectTime: any[] | string
}

const state = ref<IState>({
    buildingName: '',
    customerName: '',
    selectTime: '',
})
const _state = toRaw({
    ...state.value,
})
const columns = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '楼盘名称',
        options: async () => {
            const result = await baseList()
            return result?.map((item: any) => {
                return {
                    label: item.xmmc,
                    value: item.id,
                }
            }) ?? []
        },
        prop: 'buildingName',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '客户名称',
        prop: 'customerName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            'endPlaceholder': '请选择结束时间',
            'startPlaceholder': '请选择开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '选择时间',
        prop: 'selectTime',
        valueType: 'date-picker',
    },
]

const tabList = [
    {
        label: '全部',
        name: 'all',
    },
    {
        label: '当日',
        name: 'day',
    },
    {
        label: '本周',
        name: 'week',
    },
] as const

const activeName = ref('all')
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
type RowVO = {
    appointmentTime: string
    customerName: string
    customerStatus: string
    housingStatus: string
    intentionArea: string
    intentionBuilding: string
    intentionHouseType: string
    propertyConsultant: string
}
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'customerName', slots: { default: 'customerName' }, title: '客户名称' },
        { field: 'customerStatus', slots: { default: 'customerStatus' }, title: '客户状态' },
        { field: 'intentionBuilding', title: '意向楼盘' },
        { field: 'intentionHouseType', title: '意向户型' },
        { field: 'intentionArea', title: '意向面积' },
        { field: 'appointmentTime', title: '预约时间' },
        { field: 'housingStatus', slots: { default: 'housingStatus' }, title: '房源状态' },
        { field: 'appointmentStatus', slots: { default: 'appointmentStatus' }, title: '预约状态' },
        { field: 'propertyConsultant', title: '置业顾问' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 550,
    keepSource: true,
    showOverflow: true,
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
function rowClick(row: any) {
    push(
        {
            path: '/house-source-center/fair/reservation-information-detail',
            query: {
                id: row.id,
            },
        },
    )
}

const searchParams = computed(() => {
    return {
        objQuery: {
            buildingName: state.value.buildingName,
            customerName: state.value.customerName,
            endTime: state.value.selectTime?.[1] ? day(state.value.selectTime?.[1]).format('YYYY-MM-DD 23:59:59') : '',
            startTime: state.value.selectTime?.[0] ? day(state.value.selectTime?.[0]).format('YYYY-MM-DD 00:00:00') : '',

        },
        page: tablePage.currentPage,
        size: tablePage.pageSize,
    }
})
const { isPending, mutateAsync } = usePageInfo()
async function findList() {
    const res = await mutateAsync(searchParams.value)
    gridOptions.data = res?.records ?? []
    tablePage.total = res?.total ?? 0
}
findList()
function search() {
    tablePage.currentPage = 1
    findList()
}
function reset() {
    state.value = { ..._state }
    tablePage.currentPage = 1
    activeName.value = 'all'
    findList()
}

watch(activeName, (nval) => {
    console.log('🚀 ~ watch ~ nval:', nval)
    if (nval === 'all')
        state.value.selectTime = ''

    if (nval === 'day')
        state.value.selectTime = [day().format('YYYY-MM-DD 00:00:00'), day().format('YYYY-MM-DD 23:59:59')]

    if (nval === 'week')
        state.value.selectTime = [day().startOf('week').format('YYYY-MM-DD 00:00:00'), day().endOf('week').format('YYYY-MM-DD 23:59:59')]

    findList()
}, { deep: true })

const { isPending: exportLoading, mutateAsync: exportMutateAsync } = useExportStatistics()
async function exportFile() {
    const res = await exportMutateAsync()
    if (res)
        window.open(res)
}
</script>

<template>
    <el-button type="primary"
               class="mb-20"
               :loading="exportLoading"
               @click="exportFile"
    >
        导出
    </el-button>

    <panelGroup />

    <Charts />

    <div class="mb-20">
        <ElCard shadow="never">
            <SearchForm v-model="state"
                        :columns="columns"
                        submit-text="查询"
                        @submit="search"
                        @reset="reset"
            />
        </ElCard>
    </div>

    <el-tabs v-model="activeName"
             class="bg-#fff p-20"
    >
        <el-tab-pane v-for="item in tabList"
                     :key="item.name"
                     :label="item.label"
                     :name="item.name"
        />

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isPending"
                     row-class-name="table-row-style"
                     @page-change="handlePageChange"
        >
            <template #customerName="{ row }">
                <span class="cursor-pointer text-#0052D9 underline"
                      @click="rowClick(row)"
                >{{ row.customerName }}</span>
            </template>

            <template #customerStatus="{ row }">
                <el-tag :type="CUSTOMER_DICT[row.customerStatus]?.type">
                    {{ CUSTOMER_DICT[row.customerStatus]?.value }}
                </el-tag>
            </template>

            <template #housingStatus="{ row }">
                <span :style="{ color: HOUSING_DICT[row.housingStatus]?.color }">
                    {{ HOUSING_DICT[row.housingStatus]?.value }}
                </span>
            </template>

            <template #appointmentStatus="{ row }">
                <span :style="{ color: APPOINTMENT_DICT[row.appointmentStatus]?.color }">
                    {{ APPOINTMENT_DICT[row.appointmentStatus]?.value }}
                </span>
            </template>
        </SearchTable>
    </el-tabs>
</template>

<style>

</style>
